package serial;

import gnu.io.CommPort;
import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.Formatter;

public class TwoWaySerialComm {
	public TwoWaySerialComm() {
		super();
	}

	void connect(String portName) throws Exception {
		CommPortIdentifier portIdentifier = CommPortIdentifier
				.getPortIdentifier(portName);
		if (portIdentifier.isCurrentlyOwned()) {
			System.out.println("Error: Port is currently in use");
		} else {
			CommPort commPort = portIdentifier.open(this.getClass().getName(),
					2000);

			if (commPort instanceof SerialPort) {
				SerialPort serialPort = (SerialPort) commPort;
				serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8,
						SerialPort.STOPBITS_2, SerialPort.PARITY_NONE);

				InputStream in = serialPort.getInputStream();
				OutputStream out = serialPort.getOutputStream();

				(new Thread(new SerialReader(in))).start();
				(new Thread(new SerialWriter(out))).start();

			} else {
				System.out
						.println("Error: Only serial ports are handled by this example.");
			}
		}
	}

	public static String bytesToHexString(byte[] bytes) {
		boolean zeros = true;
		StringBuilder sb = new StringBuilder(bytes.length * 2);

		Formatter formatter = new Formatter(sb);
		for (byte b : bytes) {
			formatter.format("%02x ", b);
			if (b != 0) {
				zeros = false;
			}
		}
		if (zeros) {
			return null;
		} else {
			return sb.toString();
		}
	}

	/** */
	public static class SerialReader implements Runnable {
		InputStream in;

		public SerialReader(InputStream in) {
			this.in = in;
		}

		public static String bytesToHexString(byte[] bytes) {
			StringBuilder sb = new StringBuilder(bytes.length * 2);

			Formatter formatter = new Formatter(sb);
			for (byte b : bytes) {
				formatter.format("%02x", b);
			}

			return sb.toString();
		}

		public void run() {
			byte[] buffer = new byte[1024];
			int len = -1;
			try {
				while ((len = this.in.read(buffer)) > -1) {
					byte[] copyOf = Arrays.copyOf(buffer, len);
					System.out.print(bytesToHexString(copyOf));
					if (len > 0) {
						System.out.println();
					}
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/** */
	public static class SerialWriter implements Runnable {
		OutputStream out;

		public SerialWriter(OutputStream out) {
			this.out = out;
			try {
				this.out.write(RobokitCommands.stepperMotorRight(255, 10));
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		public void run() {

		}
	}

	public static void main(String[] args) {
		try {
			(new TwoWaySerialComm()).connect("COM1");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
